// -----------------------------
// Author: 		Dhaenens Gert	
// Creation: 	7/21/2014 10:27:30 PM				
// -----------------------------

#include "Plane.h"

Plane::Plane(RenderManager* lpRenderManager, Float fWidth, Float fDepth, UInt32 uRows, UInt32 uColumns, Bool bQuad)
	: Mesh(lpRenderManager)
{
	Mesh::VertexList vertices;
	Mesh::IndexList indices;

	Float uFaceWidth = (Float) fWidth / uRows;
	Float uFaceDepth = (Float) fDepth / uColumns;
	Vector4 vStartPosition = Vector4(0.0f, 0.0f, 0.0f, 1.0f);
	vStartPosition.x = -(fWidth / 2.0f);
	vStartPosition.z = -(fDepth / 2.0f);

	// Generate Vertices
	for (UInt32 x = 0; x < uColumns + 1; ++x)
	{
		for (UInt32 z = 0; z < uRows + 1; ++z)
		{
			Vector4 vPosition = vStartPosition;
			vPosition.x += (x * uFaceWidth);
			vPosition.z += (z * uFaceDepth);

			Vector2 vTexCoord = Vector2();
			vTexCoord.x = (1.0f / (uColumns + 1)) * x;
			vTexCoord.y = ((1.0f / (uRows + 1)) * z);

			Vertex vertex = {};
			vertex.P = vPosition;
			vertex.N = Vector3::UnitY;
			vertex.T = vTexCoord;
			
			vertices.push_back(vertex);
		}
	}

	if (!bQuad)
	{
		// Generate Triangle Patches
		// Generate Indices
		for (UInt32 x = 0; x < uColumns; ++x)
		{
			for (UInt32 z = 0; z < uRows; ++z)
			{
				// Calculate the Indices
				Index a = (z * (uColumns + 1)) + x;
				Index b = a + (uColumns + 1);
				Index c = b + 1;
				Index d = a + 1;

				indices.push_back(d);
				indices.push_back(c);
				indices.push_back(b);

				indices.push_back(d);
				indices.push_back(b);
				indices.push_back(a);
			}
		}
	}
	else
	{
		// Generate Quad Patches
		for (UInt32 x = 0; x < uColumns; ++x)
		{
			for (UInt32 z = 0; z < uRows; ++z)
			{
				// Calculate the Indices
				Index a = (z * (uColumns + 1)) + x;
				Index b = a + (uColumns + 1);
				Index c = b + 1;
				Index d = a + 1;

				indices.push_back(d);
				indices.push_back(c);
				indices.push_back(b);
				indices.push_back(a);
			}
		}
	}

	this->SetVertices(vertices);
	this->SetIndices(indices);
}

Plane::~Plane()
{
}